import React, { useState, useEffect } from 'react';
import { Table, Button, Input, Select, Space, message, Popconfirm } from 'antd';
import { SearchOutlined, PlusOutlined, ExportOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons';
import { batchDeleteUsers } from '../../api/users';
import type { Shop, UserListParams } from '../../api/users';
import './Users.css';

const Users: React.FC = () => {
    console.log('Users component rendering');
    const [shops, setShops] = useState<Shop[]>([]);
    const [loading, setLoading] = useState(false);
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });
    const [filters, setFilters] = useState<UserListParams>({
        pageCode: '1',
        pageSize: '10',
        searchValue: '',
        type: '',
        minScore: '',
        maxScore: '',
    });

    // 获取商店列表
    const fetchShops = async (params: UserListParams = {}) => {
        setLoading(true);
        try {
            console.log('调用 API 获取商店列表，参数:', { ...filters, ...params });

            // 设置模拟数据
            const mockData = [
                {
                    id: "320000198406178601",
                    shopName: "测试商店1",
                    shopAddress: "内蒙古自治区",
                    shopDescription: "不知道",
                    shopTel: "1111111111111111111",
                    shopImage: "https://ts4.tc.mm.bing.net/th/id/OIP-C.wq5h_EUUE2wrTipdzxBHJAHaFI?w=300&h=208&c=8&rs=1&qlt=90&o=6&pid=3.1&rm=2",
                    shopScore: "4",
                    shopSellCount: "9999",
                    shopType: "生鲜"
                },
                {
                    id: "450000201801294200",
                    shopName: "测试商店2",
                    shopAddress: "内蒙古自治区",
                    shopDescription: "不知道",
                    shopTel: "1111111111111111111",
                    shopImage: "https://ts4.tc.mm.bing.net/th/id/OIP-C.wq5h_EUUE2wrTipdzxBHJAHaFI?w=300&h=208&c=8&rs=1&qlt=90&o=6&pid=3.1&rm=2",
                    shopScore: "3",
                    shopSellCount: "99",
                    shopType: "水果"
                }
            ];

            setShops(mockData);
            setPagination(prev => ({
                ...prev,
                current: 1,
                total: mockData.length,
            }));

        } catch (error) {
            console.error('获取商店列表失败:', error);
            message.error('获取商店列表失败，请检查网络连接');
        } finally {
            setLoading(false);
        }
    };

    // 初始加载
    useEffect(() => {
        fetchShops();
    }, []);

    // 搜索处理
    const handleSearch = (value: string) => {
        setFilters(prev => ({ ...prev, searchValue: value }));
        fetchShops({ ...filters, searchValue: value, pageCode: '1' });
    };

    // 类型筛选
    const handleTypeFilter = (value: string) => {
        setFilters(prev => ({ ...prev, type: value }));
        fetchShops({ ...filters, type: value, pageCode: '1' });
    };

    // 评分筛选
    const handleScoreFilter = (min: string, max: string) => {
        setFilters(prev => ({ ...prev, minScore: min, maxScore: max }));
        fetchShops({ ...filters, minScore: min, maxScore: max, pageCode: '1' });
    };

    // 分页处理
    const handleTableChange = (pagination: any) => {
        const { current, pageSize } = pagination;
        setFilters(prev => ({ ...prev, pageCode: current.toString(), pageSize: pageSize.toString() }));
        fetchShops({ ...filters, pageCode: current.toString(), pageSize: pageSize.toString() });
    };

    // 批量删除
    const handleBatchDelete = async () => {
        if (selectedRowKeys.length === 0) {
            message.warning('请选择要删除的商店');
            return;
        }
        try {
            await batchDeleteUsers(selectedRowKeys as string[]);
            message.success('删除成功');
            setSelectedRowKeys([]);
            fetchShops();
        } catch (error) {
            message.error('删除失败');
        }
    };

    // 表格列配置
    const columns = [
        {
            title: '商店信息',
            dataIndex: 'shopName',
            key: 'shopName',
            render: (_: string, record: Shop) => (
                <div className="user-info">
                    <div className="user-avatar">
                        <img src={record.shopImage} alt="商店图片" style={{ width: 40, height: 40, borderRadius: '50%', objectFit: 'cover' }} />
                    </div>
                    <div className="user-details">
                        <div className="user-name">{record.shopName || '未命名商店'}</div>
                        <div className="user-email">{record.shopAddress}</div>
                    </div>
                </div>
            ),
        },
        {
            title: '类型',
            dataIndex: 'shopType',
            key: 'shopType',
            render: (type: string) => (
                <span className={`role-badge role-${type}`}>
                    {type || '未分类'}
                </span>
            ),
        },
        {
            title: '评分',
            dataIndex: 'shopScore',
            key: 'shopScore',
            render: (score: string) => (
                <span className={`status-badge status-${parseFloat(score || '0') >= 4 ? 'active' : 'inactive'}`}>
                    {score || '0'} 分
                </span>
            ),
        },
        {
            title: '销量',
            dataIndex: 'shopSellCount',
            key: 'shopSellCount',
            render: (count: string) => count || '0',
        },
        {
            title: '联系电话',
            dataIndex: 'shopTel',
            key: 'shopTel',
        },
        {
            title: '操作',
            key: 'action',
            render: (_: any, _record: Shop) => (
                <Space size="middle">
                    <Button type="link" icon={<EditOutlined />} size="small">
                        编辑
                    </Button>
                    <Popconfirm
                        title="确定要删除这个商店吗？"
                        onConfirm={() => handleBatchDelete()}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button type="link" danger icon={<DeleteOutlined />} size="small">
                            删除
                        </Button>
                    </Popconfirm>
                </Space>
            ),
        },
    ];

    console.log('Users component render, shops:', shops.length, 'loading:', loading);

    return (
        <div className="users-page" style={{
            padding: '20px',
            minHeight: '100vh',
            backgroundColor: '#f5f5f5',
            position: 'relative',
            zIndex: 1,
            display: 'block'
        }}>
            <div className="page-header">
                <h1>商店管理</h1>
                <div className="page-actions">
                    <Button type="primary" icon={<PlusOutlined />}>
                        添加商店
                    </Button>
                    <Button icon={<ExportOutlined />}>
                        导出数据
                    </Button>
                </div>
            </div>

            <div className="page-filters">
                <Space wrap>
                    <Input.Search
                        placeholder="搜索商店..."
                        style={{ width: 200 }}
                        onSearch={handleSearch}
                        enterButton={<SearchOutlined />}
                    />
                    <Select
                        placeholder="选择类型"
                        style={{ width: 120 }}
                        onChange={handleTypeFilter}
                        allowClear
                    >
                        <Select.Option value="生鲜">生鲜</Select.Option>
                        <Select.Option value="水果">水果</Select.Option>
                        <Select.Option value="冷饮">冷饮</Select.Option>
                        <Select.Option value="甜品">甜品</Select.Option>
                        <Select.Option value="鲜花">鲜花</Select.Option>
                    </Select>
                    <Input.Group compact>
                        <Input
                            style={{ width: 80 }}
                            placeholder="最低分"
                            onChange={(e) => handleScoreFilter(e.target.value, filters.maxScore || '')}
                        />
                        <Input
                            style={{ width: 80 }}
                            placeholder="最高分"
                            onChange={(e) => handleScoreFilter(filters.minScore || '', e.target.value)}
                        />
                    </Input.Group>
                </Space>
            </div>

            <div className="users-table-container">
                <Table
                    columns={columns}
                    dataSource={shops}
                    rowKey="id"
                    loading={loading}
                    pagination={{
                        current: pagination.current,
                        pageSize: pagination.pageSize,
                        total: pagination.total,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
                    }}
                    onChange={handleTableChange}
                    rowSelection={{
                        selectedRowKeys,
                        onChange: setSelectedRowKeys,
                    }}
                />
            </div>

            {selectedRowKeys.length > 0 && (
                <div className="bulk-actions">
                    <span className="selected-count">
                        已选择 {selectedRowKeys.length} 个商店
                    </span>
                    <div className="bulk-buttons">
                        <Button type="primary" danger onClick={handleBatchDelete}>
                            批量删除
                        </Button>
                    </div>
                </div>
            )}
        </div>
    );
};

export default Users;

